package com.xjoyt.pay.master.services;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xjoyt.pay.abstracts.AbstractService;
import com.xjoyt.pay.commons.ObjectUtils;
import com.xjoyt.pay.dto.ExecuteResult;
import com.xjoyt.pay.dto.PageParam;
import com.xjoyt.pay.dto.PageResult;
import com.xjoyt.pay.master.params.DistributorChannelPageParam;
import com.xjoyt.pay.master.po.DistributorChannel;
import com.xjoyt.pay.master.repository.DistributorChannelRepository;
import com.xjoyt.pay.master.vo.DistributorChannelMap;

@Service
public class DistributorChannelService extends AbstractService {

	@Autowired
	private DistributorChannelRepository repository;

	public PageResult<DistributorChannel> loadPageChannel(PageParam<DistributorChannelPageParam> param) {
		return repository.loadPageChannel(param);
	}

	/**
	 * 代理商通道删除
	 * 
	 * @param id
	 *            对象ID
	 * @return
	 */
	public ExecuteResult<?> delete(String id) {
		if (StringUtils.isBlank(id)) {
			return ExecuteResult.fail("id不能为空");
		}
		DistributorChannel entity = repository.findOne(id);
		if (entity == null) {
			return ExecuteResult.fail("代理商通道不存在");
		}
		repository.delete(id);
		return ExecuteResult.ok();
	}

	/**
	 * 新增代理商通道
	 * 
	 * @param param
	 * @return
	 */
	public ExecuteResult<?> save(DistributorChannelMap param) {
		if (param.distributor == null || param.channel == null || StringUtils.isBlank(param.distributor.id)
				|| StringUtils.isBlank(param.channel.id)) {
			return ExecuteResult.fail("数据不存在");
		}
		repository.findAllByDistributorIdAndChannelId(param.distributor.id, param.channel.id)
				.forEach(item -> repository.delete(item));
		DistributorChannel distributorChannel = new DistributorChannel();
		ObjectUtils.fieldCopy(param, distributorChannel);
		distributorChannel.id = null;
		distributorChannel.addedDate = new Date();
		distributorChannel = repository.save(distributorChannel);
		return ExecuteResult.ok();
	}
}
